﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MsgPack;
using ZeroMQ;
using NLog;


namespace Client
{
    class LprSender
    {
        private static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        private readonly string _serverAddr;

        private object _queueLock = new object();
        private List<byte[]> _lpiQueue = new List<byte[]>();



        const int maxMessageSize = 5 * 1024 * 1024;

        public LprSender(string serverAddr)
        {
            _serverAddr = serverAddr;
        }

        public void Start()
        {

            _timer = new Timer(Worker, null, TimeSpan.FromSeconds(3), TimeSpan.FromHours(1));

        }

        public void Stop()
        {
        }

        public void Send(TlvLib.Packets.LicensePlateInfo lpi)
        {
            var message = new Message.Combo();
            lpi.TimeStamp = DateTime.Now;
            message.LicensePlateInfo = lpi;

        }


        private Timer _timer;

        public void Worker(object state)
        {
            try
            {
                using (var ctx = ZmqContext.Create())
                {
                    using (var socket = ctx.CreateSocket(SocketType.REQ))
                    {
                        socket.Connect(_serverAddr);

                        Logger.Info("开始请求时间");
                        socket.Send("request timer", Encoding.UTF8);
                        var timeString = socket.Receive(Encoding.UTF8);

                        DateTime dt;
                        if (DateTime.TryParseExact(timeString, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                        {
                            Microsoft.VisualBasic.DateAndTime.TimeOfDay = dt;
                            Microsoft.VisualBasic.DateAndTime.Today = dt;
                            Logger.Info("修改系统时间成功 " + dt);
                        }
                        else
                        {
                            Logger.Error("服务器返回时间格式不正确 " + timeString);
                        }

                    }
                }
            }
            catch (ZmqException ex)
            {
                Logger.ErrorException("请求时间同步异常", ex);
            }

        }


        private static string GetReply(ZmqSocket socket)
        {
            var retryCount = 0;
            string reply = null;
            //while (true)
            {
                Logger.Info("in getreply()");
                reply = socket.Receive(Encoding.UTF8, TimeSpan.FromSeconds(2.5));
                Logger.Info("getreply() reply: " + reply);
                return reply;

            }
            // return reply;
        }
    }
}
